package net.whatmark.playavillain.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.t2framework.commons.util.Base64Util;

public class NGWordCipher {

	private static final String KEY = "T2haiku!";

	public static String decrypt(String cryptData) {
		byte[] encrypted = Base64Util.decode(cryptData);
		try {
			DESKeySpec dk = new DESKeySpec(KEY.getBytes());
			SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
			SecretKey sk = kf.generateSecret(dk);

			Cipher c = Cipher.getInstance("DES");
			c.init(Cipher.DECRYPT_MODE, sk);
			byte[] planeData = c.doFinal(encrypted); // 復号したデータ
			return new String(planeData);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String encrypt(String planeData) {
		try {
			DESKeySpec dk = new DESKeySpec(KEY.getBytes());
			SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
			SecretKey sk = kf.generateSecret(dk);
			Cipher c = Cipher.getInstance("DES");
			c.init(Cipher.ENCRYPT_MODE, sk);
			byte[] encryptData = c.doFinal(planeData.getBytes());
			return Base64Util.encode(encryptData);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
